package com.elitel.frame.web.common.page;

import com.elitel.common.utils.ServletUtils;
import com.elitel.frame.web.utils.StringUtils;
import com.github.pagehelper.PageHelper;

public class PageUtils {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    public static final String IS_ASC = "isAsc";
    /**
     * 分页参数合理化
     */
    public static final String REASONABLE = "reasonable";


    public static PageDomain getPageDomain() {
        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));
        pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));
        pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
        pageDomain.setOrderBy(getOrderBy(pageDomain.getOrderByColumn(), pageDomain.getIsAsc()));
        pageDomain.setReasonable(getReasonable(ServletUtils.getParameterToBool(REASONABLE)));
        return pageDomain;
    }


    public static void startPage() {
        PageDomain pageDomain = getPageDomain();
        if (pageDomain.getPageNum()==null) pageDomain.setPageNum(1);
        if (pageDomain.getPageSize()==null) pageDomain.setPageSize(10);
        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(), pageDomain.getOrderBy());
    }


    public static String getOrderBy(String orderByColumn, String isAsc) {
        if (StringUtils.isEmpty(orderByColumn)) {
            return "";
        }
        return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
    }

    public static Boolean getReasonable(Boolean reasonable) {
        if (StringUtils.isNull(reasonable)) {
            return Boolean.TRUE;
        }
        return reasonable;
    }
}
